<template>
	<div class="app-container">
		<div class="search-container">
			<el-form ref="queryFormRef" :model="queryParams" :inline="true">
				<el-form-item prop="keywords" label="关键字">
					<el-input v-model="queryParams.keywords" placeholder="请输入关键字" clearable @keyup.enter="handleQuery"/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery">
						<i-ep-search/>
						搜索
					</el-button>
					<el-button @click="resetQuery">
						<i-ep-refresh/>
						重置
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		
		<el-card shadow="never">
			<template #header>
				<el-button type="success" @click="openDialog()">
					<i-ep-plus/>
					新增
				</el-button>
			</template>
			
			<el-table ref="dataTableRef" v-loading="loading" :data="tableList" highlight-current-row border
								@selection-change="handleSelectionChange">
				<el-table-column label="单据号" prop="billNo" min-width="100"/>
				<el-table-column label="经销商名称" prop="dealerName" min-width="100"/>
				<el-table-column label="出库时间" prop="outboundDt" min-width="100"/>
				<el-table-column label="出库数量" prop="outboundQty" width="150"/>
				<el-table-column label="收货状态" prop="consigneeStatus" width="150">
					<template #default="scope">
						{{
							scope.row.consigneeStatus == '10' ? "未收货" :
								scope.row.consigneeStatus == '20' ? "已收货" : ""
						}}
					</template>
				</el-table-column>
				<el-table-column label="类型" prop="type" width="150">
					<template #default="scope">
						{{
							scope.row.type == '10' ? "出库单" :
								scope.row.type == '20' ? "入库单" : ""
						}}
					</template>
				</el-table-column>
				<el-table-column label="收货时间" prop="consigneeDt" width="150"/>
				<el-table-column label="备注" prop="remark" width="150"/>
				<el-table-column fixed="right" label="操作" :width="mobile === 'mobile' ? 90 : 220">
					<template #default="scope">
						<el-button type="primary" size="small" link v-if="scope.row.consigneeStatus != 20" @click="openShouhuoDialog(scope.row)">
							<i-ep-select/>
							收货
						</el-button>
						<el-button type="primary" size="small" link @click="openDialog(scope.row.id)">
							<i-ep-edit/>
							编辑
						</el-button>
						<el-button type="primary" size="small" link @click="handleDelete(scope.row.id)">
							<i-ep-delete/>
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			
			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
									v-model:limit="queryParams.pageSize" @pagination="handleQuery"/>
		</el-card>
		
		<!-- 表单弹窗 -->
		<el-dialog v-model="dialog.visible" :title="dialog.title"
							 :width="screenWidth"
							 :fullscreen="mobile === 'mobile'"
							 class="system"
							 :style="{'--mobileAddFormHeight': mobile === 'mobile' ? (screenHeight - 117) + 'px' : 'auto'}"
							 close-icon="CloseBold"
							 draggable @close="closeDialog">
			<el-form ref="dialogFormRef" :model="formData" :rules="rules" label-width="100px">
				<el-form-item label="经销商名称" prop="dealerId">
					<el-select v-model="formData.dealerId" placeholder="请选择经销商" clearable @change="handleUserChange">
						<el-option v-for="item in userSelects" :key="item.id" :label="item.name" :value="item.id"/>
					</el-select>
				</el-form-item>
				<el-form-item label="出库时间" prop="outboundDt">
					<el-date-picker
						v-model="formData.outboundDt"
						type="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						placeholder="选择日期"
					/>
				</el-form-item>
				<el-form-item label="出库数量" prop="outboundQty">
					<el-input-number v-model="formData.outboundQty" placeholder="请输入出库数量"
													 controls-position="right"
													 :min="0"/>
				</el-form-item>
				
				<el-form-item label="备注" prop="remark">
					<el-input type="textarea" v-model="formData.remark" placeholder="请输入备注"/>
				</el-form-item>
			</el-form>
			
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleSubmit">确 定</el-button>
					<el-button @click="closeDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
		
		<!-- 收货弹窗 -->
		<el-dialog v-model="shouhuoDialog.visible" :title="shouhuoDialog.title"
							 :width="screenWidth"
							 :fullscreen="mobile === 'mobile'"
							 class="system"
							 :style="{'--mobileAddFormHeight': mobile === 'mobile' ? (screenHeight - 117) + 'px' : 'auto'}"
							 close-icon="CloseBold"
							 draggable @close="closeShouhuoDialog">
			<el-form ref="dialogShouhuoFormRef" :model="formShouhuoData" :rules="shouhuoRules" label-width="100px">
				<el-form-item label="收货人" prop="consignee">
					<el-input v-model="formShouhuoData.consignee" placeholder="请输入收货人"/>
				</el-form-item>
				<el-form-item label="收货时间" prop="consigneeDt">
					<el-date-picker
						v-model="formShouhuoData.consigneeDt"
						type="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						placeholder="选择日期"
					/>
				</el-form-item>
			</el-form>
			
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleShouhuoSubmit">确 定</el-button>
					<el-button @click="closeShouhuoDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import {computed} from "vue";

defineOptions({
	name: "dept",
	inheritAttrs: false,
});

import {
	QueryRepertoryList,
	addRepertory,
	updateRepertory,
	getRepertoryForm,
	deleteRepertorys,
	shouhuoApi
} from "@/api/agency/repertory";
import {
	QueryAgencyList,
} from "@/api/agency/management";

import {getDicts} from "@/store/modules/dict";

import {useScreen} from "@/store/modules/screen";

const screenStore = useScreen()
const mobile = computed(() => (screenStore.device));
const screenHeight = computed(() => (screenStore.screenHeight));
const screenWidth = ref(700)

function initScreen() {
	if (mobile.value === 'mobile') {
		screenWidth.value = screenStore.screenWidth;
	} else {
		screenWidth.value = 700;
	}
}

import {repertoryListType, QueryForm, repertoryFormType} from "@/api/agency/repertory/types"

const queryFormRef = ref(ElForm);
const dialogFormRef = ref(ElForm);
const dialogShouhuoFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<QueryForm>({
	pageNum: 1,
	pageSize: 10,
});

const tableList = ref<repertoryListType[]>();

const dialog = reactive<DialogOption>({
	visible: false,
});

const shouhuoDialog = reactive<DialogOption>(
	{
		visible: false,
		title: "确认收货"
	}
)

const formData = reactive<repertoryFormType>({
	areaId: undefined,
	name: "",
});
const formShouhuoData = reactive<repertoryFormType>({
	consignee: "",	//1ll 收货人
	consigneeDt: "",	// 收货时间
	id: ""
});

const rules = reactive({
	dealerId: [{required: true, message: "请选择经销商", trigger: "blur"}],
});
const shouhuoRules = reactive({
	consignee: [{required: true, message: "请输入收货人", trigger: "blur"}],
	consigneeDt: [{required: true, message: "请选择收货时间", trigger: "blur"}],
});


/**
 * 查询
 */
function handleQuery() {
	loading.value = true;
	QueryRepertoryList(queryParams)
		.then(({data}) => {
			tableList.value = data.list;
			total.value = data.total;
			loading.value = false;
		})
		.finally(() => {
		});
}

/**
 * 重置查询
 */
function resetQuery() {
	
	queryFormRef.value.resetFields();
	queryParams.pageNum = 1;
	queryParams.areaId = null;
	queryParams.level = null;
	handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.deptId);
}

function filterUser(val) {
	console.log("userselect", val, userSelects.value)
	return userSelects.value.filter(item => item.id == val);
}

function handleUserChange(val) {
	console.log(val, filterUser(val)[0].name);
	formData.dealerName = filterUser(val)[0].name;
}

function openShouhuoDialog(row) {
	console.log(row)
	formShouhuoData.id = row.id;
	shouhuoDialog.visible = true;
}

const userSelects = ref([])

/**
 * 打开角色表单弹窗
 *
 * @param id
 */
function openDialog(id?: number) {
	dialog.visible = true;
	if (id) {
		dialog.title = "修改经销商信息";
		getRepertoryForm(id).then(({data}) => {
			Object.assign(formData, data);
			formData.id = id;
		});
	} else {
		// formData.id = 0;
		dialog.title = "新增经销商信息";
	}
	QueryAgencyList({pageNum: 1, pageSize: 9999}).then((data) => {
		if (data.success && data.data.list && data.data.list.length > 0) {
			userSelects.value = data.data.list;
		} else {
			userSelects.value = [];
		}
	})
}

/**
 * 角色表单提交
 */
function handleSubmit() {
	dialogFormRef.value.validate((valid: any) => {
		if (valid) {
			loading.value = true;
			const id = formData.id;
			if (id) {
				updateRepertory(id, formData)
					.then((resp) => {
						if (resp.success === true) {
							ElMessage.success(resp.msg);
							closeDialog();
							resetQuery();
						} else {
							ElMessage.warning(resp.msg);
						}
					})
			} else {
				addRepertory(formData)
					.then((resp) => {
						if (resp.success === true) {
							ElMessage.success(resp.msg);
							closeDialog();
							resetQuery();
						} else {
							ElMessage.warning(resp.msg);
						}
					})
			}
		}
	});
}

/**
 * 角色表单提交
 */
function handleShouhuoSubmit() {
	dialogShouhuoFormRef.value.validate((valid: any) => {
		if (valid) {
			loading.value = true;
			shouhuoApi(formShouhuoData)
				.then((resp) => {
					if (resp.success === true) {
						ElMessage.success(resp.msg);
						closeShouhuoDialog();
						resetQuery();
					} else {
						ElMessage.warning(resp.msg);
					}
				})
		}
	});
}

/**
 * 关闭弹窗
 */
function closeDialog() {
	dialog.visible = false;
	resetForm();
}

function closeShouhuoDialog() {
	shouhuoDialog.visible = false;
	resetShouhuoForm();
}

/**
 * 重置表单
 */
function resetForm() {
	dialogFormRef.value.resetFields();
	dialogFormRef.value.clearValidate();
	
	formData.id = undefined;
	formData.address = '';
	formData.phone = '';
	formData.name = '';
	formData.areaId = '';
}

function resetShouhuoForm() {
	dialogShouhuoFormRef.value.resetFields();
	dialogShouhuoFormRef.value.clearValidate();
	
}

/**
 * 删除
 */
function handleDelete(DeptId?: number) {
	const DeptIds = [DeptId || ids.value].join(",");
	if (!DeptIds) {
		ElMessage.warning("请勾选删除项");
		return;
	}
	
	ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(() => {
		loading.value = true;
		deleteRepertorys(DeptIds)
			.then((resp) => {
				if (resp.success === true) {
					ElMessage.success(resp.msg);
					resetQuery();
				} else {
					ElMessage.warning(resp.msg);
				}
			})
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消！'
		})
	});
}


onMounted(() => {
	initScreen()
	
	handleQuery();
});
// QueryAgencyList({pageNum: 1, pageSize: 9999}).then((data) => {
// 	if(data.success && data.data.list && data.data.list.length > 0){
// 		userSelects.value = data.data.list;
// 	}else {
// 		userSelects.value = [];
// 	}
// })

// const areaOptions = getDicts("areaTrees").filter(item => item.value == '540000');
const areaOptions = getDicts("areaTrees");

</script>

<style lang="scss" scoped>
.el-form-item__label {
	width: 120px !important;
}

.el-select {
	width: 100% !important;
}
</style>
